package com.wzdigit.wms.wms.service.inv.count;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wzdigit.framework.Shift;
import com.wzdigit.wms.basic.client.Pager;
import com.wzdigit.wms.basic.client.PagerInfo;
import com.wzdigit.wms.basic.client.response.Result;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.basic.SkuCate;
import com.wzdigit.wms.basic.domain.inventory.Lotno;
import com.wzdigit.wms.basic.enums.inventory.count.dif.InvIsDifEnum;
import com.wzdigit.wms.basic.enums.inventory.count.dtl.InvDtlStatusEnum;
import com.wzdigit.wms.basic.enums.inventory.count.dtl.InvIsReplayEnum;
import com.wzdigit.wms.basic.enums.inventory.count.dtl.InvTaskTypeEnum;
import com.wzdigit.wms.basic.enums.inventory.count.goods.InvIsExitEnum;
import com.wzdigit.wms.basic.enums.inventory.count.header.InvHeaderStatusEnum;
import com.wzdigit.wms.basic.util.HttpSessionUtil;
import com.wzdigit.wms.wms.client.request.inv.count.dto.ReTaskDto;
import com.wzdigit.wms.wms.domain.inv.count.InvCountDtl;
import com.wzdigit.wms.wms.domain.inv.count.InvCountDtlGoods;
import com.wzdigit.wms.wms.domain.inv.count.InvCountHeader;
import com.wzdigit.wms.wms.mapper.inv.count.InvCountDtlGoodsMapper;
import com.wzdigit.wms.wms.mapper.inv.count.InvCountDtlMapper;
import com.wzdigit.wms.wms.mapper.inv.count.InvCountHeaderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 复盘任务BS Service
 * Created by zyf on 2021/10/16 10:48
 */
@Slf4j
@Service
public class InvReCountService {
    @Autowired
    private InvCountHeaderMapper headerMapper;
    @Autowired
    private InvCountDtlMapper dtlMapper;
    @Autowired
    private InvCountDtlGoodsMapper goodsMapper;

    //复盘批次号下拉框
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<Lotno>> searchReLot(BigDecimal headerId, Pager<?> pager){
        Page<Lotno> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        PagerInfo<List<Lotno>> pagerInfo = new PagerInfo<>();
        List<Lotno> datas = dtlMapper.selectReLotnos(headerId);
        pagerInfo.setTotalCount(page.getTotal());
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //复盘物料分类下拉框
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<SkuCate>> searchReCate(BigDecimal headerId, Pager<?> pager){
        Page<SkuCate> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        PagerInfo<List<SkuCate>> pagerInfo = new PagerInfo<>();
        List<SkuCate> datas = dtlMapper.selectCates(headerId);
        pagerInfo.setTotalCount(page.getTotal());
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //复盘物料编码下拉框
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PagerInfo<List<Sku>> searchReSku(BigDecimal headerId, Pager<?> pager){
        Page<Sku> page = PageHelper.offsetPage(pager.getSkipCount(), pager.getMaxResultCount());
        PagerInfo<List<Sku>> pagerInfo = new PagerInfo<>();
        List<Sku> datas = dtlMapper.selectSkus(headerId);
        pagerInfo.setTotalCount(page.getTotal());
        pagerInfo.setItems(datas);

        return pagerInfo;
    }

    //生成复盘任务
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<String> createReTask(ReTaskDto taskDto,HttpServletRequest servletRequest) throws Exception{
        Date nowDate=new Date();
        String loginName= HttpSessionUtil.getLoginName(servletRequest);

        BigDecimal headerId = taskDto.getInvCountHeaderId();
        InvCountHeader header = headerMapper.selectOne(new QueryWrapper<InvCountHeader>().eq("INV_COUNT_HEADER_ID", headerId));
        if (!header.getStatus().equals(InvHeaderStatusEnum.FINISH_INV.code)&&!header.getStatus().equals(InvHeaderStatusEnum.RESULT_FAIL_APPROVED.code)){
            Shift.fatal("仅["+InvHeaderStatusEnum.FINISH_INV.enumName+"/"+InvHeaderStatusEnum.RESULT_FAIL_APPROVED.enumName+"]才可复盘!");
        }

        //查询需要复盘的任务ID
        List<BigDecimal> reCountDtlIds=new ArrayList<>();
        if (!CollectionUtil.isEmpty(taskDto.getSkuIds())){
            reCountDtlIds.addAll(dtlMapper.selectReIds(headerId,taskDto.getLotnos(),taskDto.getSkuIds()));
        }
        if (taskDto.getIsDifReCount()!=null){
            if (taskDto.getIsDifReCount().equals(InvIsDifEnum.YES.code)){
                reCountDtlIds.addAll(dtlMapper.selectDifReIds(headerId));
            }
        }
        if (CollectionUtil.isEmpty(reCountDtlIds)){
            Shift.fatal("查无需要复盘的记录!");
        }
        //去重
        reCountDtlIds=reCountDtlIds.stream().distinct().collect(Collectors.toList());
        //查询最大的行数
        int max = dtlMapper.selectMaxLineNo(headerId);max++;
        //查询盘点任务信息
        List<InvCountDtl> dtlList = dtlMapper.selectList(new QueryWrapper<InvCountDtl>().in("INV_COUNT_DTL_ID", reCountDtlIds));
        //查询盘点SN信息
        List<InvCountDtlGoods> goodsList = goodsMapper.selectList(new QueryWrapper<InvCountDtlGoods>().in("INV_COUNT_DTL_ID", reCountDtlIds));
        Map<BigDecimal,List<InvCountDtlGoods>> goodsMap=new HashMap<>();
        if (!CollectionUtil.isEmpty(goodsList)){
            goodsMap = goodsList.stream().collect(Collectors.groupingBy(InvCountDtlGoods::getInvCountDtlId));
        }
        for (InvCountDtl invCountDtl : dtlList) {
            log.info("["+invCountDtl.toString()+"]生成复盘任务");
            //新增复盘任务
            InvCountDtl insertDto=new InvCountDtl();
            insertDto.setInvCountHeaderId(headerId);
            insertDto.setInvCountLineNo(max);
            insertDto.setTaskType(InvTaskTypeEnum.RE_COUNT.code);
            //新增的复盘任务的关联盘点任务ID
            insertDto.setRelationTaskId(invCountDtl.getInvCountDtlId());
            insertDto.setFactory(invCountDtl.getFactory());
            insertDto.setSkuId(invCountDtl.getSkuId());
            insertDto.setVendor(invCountDtl.getVendor());
            insertDto.setInvAttr(invCountDtl.getInvAttr());
            insertDto.setQaStatus(invCountDtl.getQaStatus());
            insertDto.setLotno(invCountDtl.getLotno());
            insertDto.setWhsId(invCountDtl.getWhsId());
            insertDto.setZoneId(invCountDtl.getZoneId());
            insertDto.setLocId(invCountDtl.getLocId());
            insertDto.setAccountQty(invCountDtl.getAccountQty());
            insertDto.setReCountId(BigDecimal.ZERO);
            insertDto.setCountQty(BigDecimal.ZERO);
            insertDto.setReCount(InvIsReplayEnum.NO.code);
            insertDto.setUnit(invCountDtl.getUnit());
            insertDto.setStatus(InvDtlStatusEnum.CREATE.code);
            insertDto.setCreateUser(loginName);
            insertDto.setCreateTime(nowDate);
            dtlMapper.insert(insertDto);
            max++;

            //新增盘点SN
            List<InvCountDtlGoods> insertGoodsList = goodsMap.get(invCountDtl.getInvCountDtlId());
            if (!CollectionUtil.isEmpty(insertGoodsList)){
                for (InvCountDtlGoods goods : insertGoodsList) {
                    InvCountDtlGoods dtlGoods=new InvCountDtlGoods();
                    dtlGoods.setInvCountDtlId(insertDto.getInvCountDtlId());
                    dtlGoods.setGoodsSn(goods.getGoodsSn());
                    dtlGoods.setGoodsId(goods.getGoodsId());
                    dtlGoods.setAccountQty(goods.getAccountQty());
                    dtlGoods.setCountQty(BigDecimal.ZERO);
                    dtlGoods.setAccountLoc(goods.getAccountLoc());
                    dtlGoods.setIsExist(InvIsExitEnum.NO.code);
                    dtlGoods.setStatus(goods.getStatus());
                    dtlGoods.setCreateUser(loginName);
                    dtlGoods.setCreateTime(nowDate);
                    goodsMapper.insert(dtlGoods);
                }
            }
            //更新旧任务的最后复盘任务ID
            List<BigDecimal> oldIds=new ArrayList<>();
            oldIds.add(invCountDtl.getInvCountDtlId());
            //存父任务的ID
            while (invCountDtl.getRelationTaskId()!=null&&invCountDtl.getRelationTaskId().compareTo(BigDecimal.ZERO)!=0){
                oldIds.add(invCountDtl.getRelationTaskId());
                invCountDtl=dtlMapper.selectOne(new QueryWrapper<InvCountDtl>().eq("INV_COUNT_DTL_ID",invCountDtl.getRelationTaskId()));
            }
            dtlMapper.updateReplayInfo(oldIds,insertDto.getInvCountDtlId(),loginName);
        }
        //更新主档状态
        headerMapper.updateHeaderStatus(loginName, InvHeaderStatusEnum.WAIT_REL_INV.code, Arrays.asList(headerId));

//        Shift.fatal("?//////");
        return new Result<>("生成复盘任务成功!");
    }

}
